<template>
  <div class="real-time-wrapper"  @dblclick="initTb">
    <div class="cal-fee">
      <Drawer
        title="计算保费"
        v-model="value3"
        width="350"
        :mask-closable="false"
        :styles="styles"
      >
        <Form :model="feeFormData">
          <Row :gutter="32">
            <Col span="12">
              <FormItem label="险种" label-position="top">
                <Select v-model="feeFormData.riskCode" placeholder="请选择险种" @on-change="selectShow">
                  <Option v-for="item in riskCodes" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="amntShow">
              <FormItem label="保额" label-position="top">
                <Input v-model="feeFormData.amnt" placeholder="请输入保额" />
              </FormItem>
            </Col>
            <Col span="12" v-if="levelShow">
              <FormItem label="档次" label-position="top">
                <Select v-model="feeFormData.level" placeholder="请选择档次">
                  <Option v-for="item in level" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="riskWrapShow">
              <FormItem label="套餐编码" label-position="top">
                <Select v-model="feeFormData.riskWrap" placeholder="请选择套餐">
                  <Option v-for="item in riskWrap" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12"  v-if="payIntvShow">
              <FormItem label="缴费频次" label-position="top">
                <Select v-model="feeFormData.payIntv" placeholder="请选择">
                  <Option v-for="item in payIntvs" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="genderShow">
              <FormItem label="性别" label-position="top">
                <Select v-model="feeFormData.gender" placeholder="请选择">
                  <Option v-for="item in genders" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="ageShow">
              <FormItem label="年龄" label-position="top">
                <Input v-model="feeFormData.age" placeholder="请输入年龄" />
              </FormItem>
            </Col>
            <Col span="12" v-if="socialShow">
              <FormItem label="有无社保" label-position="top">
                <Select v-model="feeFormData.socialFlag" placeholder="请选择">
                  <Option v-for="item in socialFlag" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="xbShow">
              <FormItem label="是否续保" label-position="top">
                <Select v-model="feeFormData.xbFlag" placeholder="请选择">
                  <Option v-for="item in xbFlag" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="12">
              <div class="demo-drawer-footer1">
                <Button style="margin-right: 8px" @click="value3 = false">取消</Button>
                <Button type="primary" @click="calFee()">开始计算</Button>
              </div>
            </Col>
          </Row>
          <br>
          <Row :gutter="32">
            <Col  span="24">
              <h1 v-if="calSucc" style="color: red">计算结果：{{result_fee}}分</h1>
            </Col>
          </Row>
        </Form>
      </Drawer>
    </div>
    <div class="excel-upload" v-show="excelShow">
      <Card title="导入投保数据">
        <Row>
          <Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
            <Button icon="ios-cloud-upload-outline" :loading="uploadLoading" @click="handleUploadFile">上传文件</Button>
          </Upload>
        </Row>
        <Row>
          <div class="ivu-upload-list-file" v-if="file !== null">
            <Icon type="ios-stats"></Icon>
            {{ file.name }}
            <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove" @click.native="handleRemove()"></Icon>
          </div>
        </Row>
        <Row>
          <transition name="fade">
            <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
              <div v-if="progressPercent == 100">
                <Icon type="ios-checkmark-circle"></Icon>
                <span>成功</span>
              </div>
            </Progress>
          </transition>
        </Row>
      </Card>
    </div>
    <Card title="投保数据：" class="tb-table">
      <!--<p class="table-header" @dblclick="initTb">投保数据:</p>-->
      <Table border
             stripe
             @on-row-dblclick="calPrem"
             ref="selection"
             :columns="tbTableHeader"
             @on-selection-change="multiSelection"
             :data="tbDatas.slice((currentPage-1)*pageSize,currentPage*pageSize)">
      </Table>
      <Row class="page">
        <Col span="10">
          <Page
            :total="tbDatas.length"
            :page-size="pageSize"
            :page-size-opts=[3,5,10,20]
            size="small"
            @on-change="currentChange"
            @on-page-size-change="pageSizeChange"
            show-total
            show-elevator
            show-sizer />
        </Col>
        <Col span="10">
          <Button @click="tb" type="primary">投保</Button>
        </Col>
      </Row>
      <Modal v-model="modal2" width="360">
        <p slot="header" style="color:#f60;text-align:center">
          <Icon type="ios-information-circle"></Icon>
          <span>出单确认</span>
        </p>
        <div style="text-align:center">
          <p>如果继续，此对话框将在所有数据投保结束后关闭</p>
          <p>是否继续？</p>
        </div>
        <div slot="footer">
          <Button type="error" size="large" long :loading="modal_loading" @click="getTestResult">{{loadingMsg}}</Button>
        </div>
      </Modal>
    </Card>
    <Card title="投保结果:" v-if="tbResultShow" class="tb-result" >
      <Table border
             stripe
             :row-class-name="errorRes"
             ref="selection"
             :columns="tbResultHeader"
             :data="tbResultDatas.slice((currentPage-1)*pageSize,currentPage*pageSize)">
      </Table>
      <Row class="page">
        <Col span="10">
          <Page
            :total="tbResultDatas.length"
            :page-size="pageSize"
            :page-size-opts=[3,5,10,20]
            size="small"
            @on-change="currentChange"
            @on-page-size-change="pageSizeChange"
            show-total
            show-elevator
            show-sizer />
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script>
import excel from '../../../assets/util/excel.js'
export default {
  name: 'real-time',
  data () {
    return {
      xbShow: true,
      riskWrapShow: true,
      excelShow: true,
      tbResultShow: false,
      socialShow: true,
      amntShow: true,
      ageShow: true,
      genderShow: true,
      payIntvShow: true,
      levelShow: true,
      modal2: false,
      modal_loading: false,
      loadingMsg: '继续',
      uploadLoading: false,
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableLoading: false,
      calFeeObj: {},
      calFeeObjIndex: 0,
      value3: false,
      currentPage: 1,
      pageSize: 5,
      result_fee: 0,
      multiSelectData: [],
      calSucc: false,
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      riskCodes: [
        '123703',
        '123903',
        '124302',
        '124701',
        '220702',
        '220802',
        '221402'
      ],
      riskWrap: [
        'ZZJ228',
        'ZZJ229'
      ],
      socialFlag: [
        {
          value: '1',
          label: '有'
        },
        {
          value: '0',
          label: '无'
        }
      ],
      xbFlag: [
        {
          value: '1',
          label: '是'
        },
        {
          value: '0',
          label: '否'
        }
      ],
      genders: [
        {
          value: '0',
          label: '男'
        },
        {
          value: '1',
          label: '女'
        }
      ],
      payIntvs: [
        {
          value: '1',
          label: '月缴'
        },
        {
          value: '12',
          label: '年缴'
        }
      ],
      level: [
        1,
        2,
        3
      ],
      feeFormData: {
        riskCode: '',
        amnt: '',
        level: '',
        socialFlag: '',
        xbFlag: '',
        payIntv: '',
        gender: '',
        riskWrap: '',
        age: ''
      },
      tbDatas: [],
      tbResultDatas: [],
      tbTableHeader: [
        {
          title: '产品编码',
          key: 'productCode'
        },
        {
          title: '保额',
          key: 'amnt'
        },
        {
          title: '投保申请日期',
          key: 'applyDate'
        },
        {
          title: '生效日期',
          key: 'effectiveDate'
        },
        {
          title: '产品编码2',
          key: 'produceCode2'
        },
        {
          title: '投保人姓名',
          key: 'appntName'
        },
        {
          title: '投保人证件类型',
          key: 'appntIdType'
        },
        {
          title: '投保人证件号',
          key: 'appntIdNo'
        },
        {
          title: '投被保人关系',
          key: 'relation'
        },
        {
          title: '被保人姓名',
          key: 'insuredName'
        },
        {
          title: '被保人证件类型',
          key: 'insuredIdType'
        },
        {
          title: '被保人证件号',
          key: 'insuredIdNo'
        },
        {
          title: '社保类型',
          key: 'socialType'
        },
        {
          title: '保费',
          key: 'prem'
        }
      ],
      tbResultHeader: [
        {
          title: '投保人姓名',
          key: 'appName'
        },
        {
          title: '投保结果',
          key: 'success'
        },
        {
          title: '错误代码',
          key: 'errorCode'
        },
        {
          title: '结果描述',
          key: 'errorMessage'
        },
        {
          title: '订单号',
          key: 'policyNo'
        },
        {
          title: '保单号',
          key: 'outPolicyNo'
        },
        {
          title: '电子保单地址',
          key: 'policyUrl'
        }
      ]
    }
  },
  methods: {
    initTb () {
      this.excelShow = !this.excelShow
    },
    currentChange (current) {
      this.currentPage = current
    },
    multiSelection (selection) {
      this.multiSelectData = selection
      console.log('改变，当前选中数：：' + this.multiSelectData.length)
    },
    pageSizeChange (size) {
      this.pageSize = size
    },
    errorRes (row, index) {
      if (row.success === '0') {
        return 'demo-table-error-row'
      }
      return ''
    },
    initShow () {
      this.amntShow = true
      this.levelShow = true
      this.payIntvShow = true
      this.genderShow = true
      this.socialShow = true
      this.ageShow = true
      this.xbShow = true
      this.riskWrapShow = false
    },
    selectShow (value) {
      this.initShow()
      if (value === '123703' || value === '123903') {
        this.amntShow = false
        this.genderShow = false
        this.socialShow = false
      }
      if (value === '220702' || value === '220802') {
        this.levelShow = false
        this.payIntvShow = false
        this.socialShow = false
        this.xbShow = false
      }
      if (value === '221402') {
        this.amntShow = false
        this.payIntvShow = false
        this.socialShow = false
        this.xbShow = false
      }
      if (value === '124701') {
        this.amntShow = false
        this.genderShow = false
        this.socialShow = false
      }
      if (value === '124302') {
        this.riskWrapShow = true
        this.amntShow = false
        this.genderShow = false
        this.socialShow = false
      }
    },
    tb () {
      if (this.tbDatas.length === 0) {
        this.$Message.error({
          content: '一条数据都没有，投个屁啊，回去准备数据',
          duration: 3
        })
        return false
      }
      this.modal2 = true
    },
    calPrem (obj, index) {
      this.feeFormData = {}
      this.feeFormData.amnt = obj.amnt
      this.calSucc = false
      this.result_fee = 0
      let arrIndex = (index + (this.currentPage - 1) * this.pageSize)
      this.calFeeObj = obj
      this.calFeeObjIndex = arrIndex
      this.value3 = true
    },
    calFee () {
      this.calSucc = false
      this.$axios({
        url: '/cal/fee',
        method: 'POST',
        data: {
          tradeMap: {
            'com.sinosoft.lis.entity.FeeCalFactorPojo': this.feeFormData
          }
        }
      }).then((res) => {
        let tradeInfo = res.data
        let errList = tradeInfo.errorList
        if (errList && errList.length > 0) {
          this.$Message.error({
            content: errList[0],
            duration: 5
          })
        } else {
          this.calSucc = true
          this.result_fee = tradeInfo.tradeMap.feeResult
          this.$Message.success('计算成功，请保存好结果以防丢失')
          this.calFeeObj.prem = this.result_fee
          this.tbDatas.splice(this.calFeeObjIndex, 1, this.calFeeObj)
          // console.log(JSON.stringify(this.multiSelectData[0]))
        }
      }).catch((error) => {
        console.log('调用保费计算接口发生异常' + JSON.stringify(error))
        this.$Message.error('系统异常，保费计算失败')
      })
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    handleUploadFile () {
      this.initUpload()
    },
    initUpload () {
      this.file = null
      this.showProgress = false
      this.tbDatas = []
      this.tbResultDatas = []
      this.tbResultShow = false
    },
    handleRemove () {
      this.initUpload()
      this.$Message.info('上传的文件已删除！')
    },
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
        this.showProgress = true
      }
      reader.onprogress = e => {
        this.progressPercent = Math.round(e.loaded / e.total * 100)
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const { results } = excel.read(data, 'array')
        // const tableTitle = header.map(item => { return { title: item, key: item } })
        console.log(JSON.stringify(results))
        this.tbDatas = results
        // this.tableTitle = tableTitle
        this.uploadLoading = false
        this.tableLoading = false
        this.showRemoveFile = true
      }
    },
    getTestResult () {
      this.modal_loading = true
      this.$axios({
        url: '/cal/get_tb_result',
        method: 'POST',
        data: {
          tradeMap: {
            'com.sinosoft.lis.entity.PolFactorPojo': this.tbDatas,
            'serviceType': 'ant-pol'
          }
        }
      }).then((res) => {
        let tradeInfo = res.data
        let errList = tradeInfo.errorList
        if (errList && errList.length > 0) {
          this.$Message.error(errList[0])
        } else {
          console.log('返回数据：：' + JSON.stringify(tradeInfo))
          this.tbResultDatas = tradeInfo.tradeMap['com.sinosoft.lis.entity.PolResultPojo']
        }
      }).catch((error) => {
        console.log('调用投保接口发生异常' + JSON.stringify(error))
        this.$Message.error('系统异常，投保失败')
      })
      this.modal_loading = false
      this.modal2 = false
      this.$Message.success('出单结束，请查看详情')
      this.tbResultShow = true
      this.excelShow = false
    }
  }
}
</script>

<style>
  .ivu-table .demo-table-error-row td{
    color: red;
    font-weight: bold ;
  }
  .table-header{
    font-weight: bold ;
    font-size: 15px;
    padding-top: 4px;
    padding-left: 4px;
  }
  .demo-drawer-footer{
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
  .page{
    padding-top: 10px;
    padding-left: 20px;
  }
</style>
